import {isNative} from "../../shared/util";

export let isUsingMicroTask = false;

const callbacks = [];
let pending = false;

function flushCallBack () {
    pending = false;
    const copies = callbacks.slice();
    callbacks.length = 0;
    for (let i=0; i<copies.length; i++) {
        copies[i]();
    }
}

let timerFunc = null;

if ( Promise !== undefined && isNative(Promise) ) {
    const p = Promise.resolve();
    timerFunc = () => {
        p.then(flushCallBack);
    }
}
else {
    timerFunc = () => {
        setTimeout(flushCallBack, 0);
    }
}

/**
 * 添加下一次刷新循环前的回调
 * @param {Function} cb
 * @param {Object} ctx
 */
export function nextTick (cb, ctx) {
    let _resolve;
    callbacks.push(() => {
        if (cb) {
            try {
                cb.call(ctx);
            } catch (e) {
                console.error(e);
                // todo handleError
            }
        }
        else if (_resolve) {
            _resolve(ctx);
        }
    });
    if (!pending) {
        pending = true;
        timerFunc();
    }
    if (!cb && typeof Promise !== undefined) {
        return new Promise(resolve => {
            _resolve = resolve;
        });
    }
}
